package com.siwei.mes.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.tgl.TglTjlbycl;
import com.siwei.mes.mapper.TglTjlbyclMapper;
import com.siwei.mes.service.TglTjlbyclService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * TGL-tjlbycl(TglTjlbycl)表服务实现类
 *
 * @author linzi
 * @since 2023-12-09 12:01:18
 */
@Service
public class TglTjlbyclServiceImpl implements TglTjlbyclService {
    private static final Logger log = LoggerFactory.getLogger("tgl");
    @Resource
    private TglTjlbyclMapper tglTjlbyclMapper;

    @Override
    public Long create(TglTjlbycl entity) {
        tglTjlbyclMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public void update(TglTjlbycl entity) {
        TglTjlbycl tglTjlbycl = tglTjlbyclMapper.selectByPrimaryKey(entity.getId());
        assertTrue(tglTjlbycl == null, "TGL-tjlbycl信息不存在");
        tglTjlbyclMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        TglTjlbycl tglTjlbycl = tglTjlbyclMapper.selectByPrimaryKey(id);
        assertTrue(tglTjlbycl == null, "TGL-tjlbycl信息不存在");
        tglTjlbyclMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<TglTjlbycl> getPage(PageQuery<TglTjlbycl, TglTjlbycl> query) {
        TglTjlbycl searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> tglTjlbyclMapper.getList(searchParam));
    }

    @Override
    public TglTjlbycl loadById(Long id) {
        return tglTjlbyclMapper.loadById(id);
    }

    @Override
    public List<TglTjlbycl> getAll(TglTjlbycl entity) {
        return tglTjlbyclMapper.getList(entity);
    }

    @Override
    public void operateTglTjlbycl(TglTjlbycl entity) {
        log.info("TGL新增或修改原材料消耗,入参：{}", JSON.toJSONString(entity));
        /**根据Id判断是否存在*/
        TglTjlbycl localInfo = tglTjlbyclMapper.selectByFid(entity.getFid());
        if (localInfo != null) {
            if (ObjectUtil.isEmpty(localInfo.getSynctime()) || entity.getSynctime() > localInfo.getSynctime()) {
                entity.setId(localInfo.getId());
                tglTjlbyclMapper.updateByPrimaryKeySelective(entity);
            }
        } else {
            tglTjlbyclMapper.insertSelective(entity);
        }
    }
}
